const moment = require("moment")

//延迟
const delay = time => new Promise((s)=>setTimeout(s,time))

//计算间隔 返回时间戳
const juageBuyInterval = ({amount_month,coinList}) =>{

	const perAmount = coinList.map(v => v.amount).reduce((s,v)=> s+v,0)

	const buyAcountForMonth = amount_month/perAmount;

	return 30*24*60*60*1000/buyAcountForMonth;
}



const main = (allConfig,allService) => {

	const {account,runtime} = allConfig;
	const {lifeCircleService,coinOrderService,txLogService,sysLogService,emailService} = allService;

	//发送错误信息
	const throwError = async errorMsg => {
			//日志:更新订单时间戳 防止在心跳内重复提醒
			lifeCircleService.update({lastOrderStamp:moment().valueOf(),msg:errorMsg}).flush();
			//日志:记录错误信息到日志
			sysLogService.appendJson({state:"error",msg:errorMsg});
			//邮件:发送错误信息到邮件
			if(emailService){
				await emailService.error(errorMsg);
			}
			return;
	}

	//购买间隔
	const buyInterval = juageBuyInterval(runtime)

	//记录启动日志
	lifeCircleService.update({lastStarDate:moment().format('YYYY-MM-DD HH:mm'),buyInterval:(buyInterval/1000/60/60).toFixed(2)+"小时",msg:"系统启动正常"}).flush();

	console.log("启动信息:",lifeCircleService.data);

	//心跳方法 周期一分钟
	setInterval(async ()=>{

		try{

			//距离上次下单时间 大于购买间隔
			if(moment().valueOf() - lifeCircleService.getLastOrderTime() > buyInterval){


				for(let coinIndex in runtime.coinList){

					const {name,amount,fixed} = runtime.coinList[coinIndex]

					const price  = await coinOrderService.getTicker(name)
					await delay(500)
					
					const balance = await coinOrderService.getUSDTBalance()
					await delay(500)

					//余额不足
					if(balance < amount){
						await throwError(`余额不足.需要:${amount}USDT,账户剩余:${balance}USDT`);
						return;
					}

					//下单号
					const {ordId} = await coinOrderService.marketOrder(name,amount);

					//订单记录
					const recordOrder = {
							name,
							ordId,
							buySize:(amount/price).toFixed(fixed),
							balance:(balance-amount).toFixed(2),
							price,
							amount
					};

					//日志:记录下单成功信息
					txLogService.orderSuccess(recordOrder);

					//系统:更新周期函数
					lifeCircleService.addAmount(amount,{[name]:price},balance);

					//邮件:发送订单信息
					if(emailService){
						await emailService.orderSuccess({order:recordOrder,system:lifeCircleService.data});
					}

					await delay(5*1000);//延迟5秒下单
				}

			}

			//更新心跳时间
			lifeCircleService.update({lastHeartBeat:moment().format('YYYY-MM-DD HH:mm:ss'),msg:"系统运行正常"}).flush();

			console.log("心跳信息:",lifeCircleService.data);


		}catch(e){
			await throwError(`系统出现错误:${e}`);
		}

	},60*1000)

}


module.exports = {main};